package com.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;


/**
 * 数据库连接配置
 *
 */
@Configuration
public class DataSourceConfig {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);



    @Value("${master.jdbc.driver}")
    private String driver;
    @Value("${master.jdbc.username}")
    private String username;
    @Value("${master.jdbc.url}")
    private String url;
    @Value("${master.jdbc.password}")
    private String password;

    @Value("${master.jdbc.pool.initSize}")
    private int initSize;
    @Value("${master.jdbc.pool.initSize}")
    private int minIdle;
    @Value("${master.jdbc.pool.initSize}")
    private int maxActive;


    @Bean
    public DataSource masterDataSource(){
        DruidDataSource dataSource=new DruidDataSource();
       dataSource.setUrl(url);
       dataSource.setUsername(username);
       dataSource.setPassword(password);
       //设置连接池初始化大小，以及空闲，最大数量
       dataSource.setInitialSize(initSize);
       dataSource.setMinIdle(minIdle);
       dataSource.setMaxActive(maxActive);

       //配置获取连接等待超时的时间
       dataSource.setMaxWait(60000);

       //配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
       dataSource.setTimeBetweenEvictionRunsMillis(60000);

       //配置一个连接在池中最小生存的时间，单位是毫秒
       dataSource.setMinEvictableIdleTimeMillis(300000);

       dataSource.setValidationQuery("SELECT 'x'");
       dataSource.setTestWhileIdle(true);
       dataSource.setTestOnBorrow(false);
       dataSource.setTestOnReturn(false);

       //关闭PSCache，并且指定每个连接上PSCache的大小
       //dataSource.setPoolPreparedStatements(false);
       //dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);


       return  dataSource;

    }


}
